<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>单词距离</title>
  </head>
  <body>
    <script>
      //     有个内含单词的超大文本文件，给定任意两个不同的单词，找出在这个文件中这两个单词的最短距离(相隔单词数)。如果寻找过程在这个文件中会重复多次，而每次寻找的单词不同，你能对此优化吗?

      // 示例：

      // 输入：words = ["I","am","a","student","from","a","university","in","a","city"], word1 = "a", word2 = "student"
      // 输出：1

      // 来源：力扣（LeetCode）
      // 链接：https://leetcode.cn/problems/find-closest-lcci
      // 著作权归领扣网络所有。商业转载请联系官方授权，非商业转载请注明出处。

      /**
       * @param {string[]} words
       * @param {string} word1
       * @param {string} word2
       * @return {number}
       */
      var findClosest = function (words, word1, word2) {
        let arr1 = []
        let arr2 = []
        for (let i = 0; i < words.length; i++) {
          if (words[i] === word1) {
            arr1.push(i)
          }
          if (words[i] === word2) {
            arr2.push(i)
          }
        }
        if (!arr1[0] || !arr2[0]) {
          return undefined
        }
        let min = Math.abs(arr1[0] - arr2[0])
        // console.log(arr2[0])
        for (let i = 0; i < arr1.length; i++) {
          for (let j = 0; j < arr2.length; j++) {
            min = Math.min(min, Math.abs(arr1[i] - arr2[j]))
          }
        }
        return min
      }
      let words = ['I', 'am', 'a', 'student', 'from', 'a', 'university', 'in', 'a', 'city'],
        word1 = 'a',
        word2 = 'student'
      console.log(findClosest(words, word1, word2))
    </script>
  </body>
</html>
